package com.twu.biblioteca;

class ControllerManager implements InputDispatcher.Handler {

    private Controller controller;

    ControllerManager(Controller initialController) {
        this.controller = initialController;
    }

    @Override
    public void init() {
        controller.enter();
    }

    @Override
    public void handle(String input) {
        if (isFinished()) {
            throw new IllegalStateException();
        }
        Controller handlingController = controller;
        Controller resultingController = controller.handle(input);
        if (handlingController.equals(resultingController) == false) {
            resultingController.enter();
        }
        controller = resultingController;
    }

    boolean isFinished() {
        return controller == NullController.getInstance();
    }

    @Override
    public boolean isClosed() {
        return isFinished();
    }

}
